<template>
	<view class="pageWrap">
		<view class="background"></view>
		<!-- <cus-nav :goback="goBack" :title="pageTitle"></cus-nav> -->
		<!--question area-->
		<view class="testPager" v-if="loaded">
			<!--pre and next-->
			<!-- <view class="questionChange clear">
				<view class="changeBtn left"  hover-class="btnHover" v-show="curIndex > 0" @click="preProblem">上一题</view>
				<view class="changeBtn right"  hover-class="btnHover" v-show="nextShow" @click="nextProblem">下一题</view>
			</view> -->
			<view class="questionChange clear">
				<view class="changeBtn reflect1 left"  hover-class="btnHover" v-show="curIndex > 0" @click="preProblem"></view>
				<view class="changeBtn reflect1 right"  hover-class="btnHover" v-show="nextShow" @click="nextProblem"></view>
				<text>{{curIndex + 1}}/{{taskContent.questions.length}}</text>
			</view>
			<!--作答区域-->
			<view class="questionArea">
				<!--声源控制-->
				<view class="toolbar" v-show="false">
					<image v-if="backOn" @click="rotateToggle" class="backMusic" src="../../static/img/test/backToogle.png"></image>
					<image v-if="!backOn" @click="rotateToggle" src="../../static/img/test/backToogleGrey.png"></image>
<!-- 					<image v-if="!soundOn" @click="speekTitle" src="../../static/img/test/soundOff.png"></image>
					<image v-else @click="speekTitle" src="../../static/img/test/soundOn.png"></image> -->
					<view class="questionType reflect1 center fpt28" v-show="questionType">
						<!-- <image class="dec1" src="../../static/img/test/dec1.png"></image> -->
						{{questionType}}
						<!-- <image class="dec2" src="../../static/img/test/dec2.png"></image> -->
					</view>
					<view @click="openParagraph" v-show="paragraphContent" class="reader reflect1 center fpt28">阅读文章</view>
				</view>
				<view class="tip center" v-if="currentQuestion && currentQuestion.questiontype === 5">
					请按住图标<image src="../../static/img/test/drag.png"></image>拖动项目进行排序
				</view>
				<view style="margin-left: 76rpx;position: relative">
						<question-item @skip="skip" @updateAnswer="updateAnswer" ref="questionItem" :question="currentQuestion" :answer="currentAnswer"></question-item>
				</view>
				<view class="nextOne">
					<view class="submit" :class="{disSubmit:isdisable}" @click="submitAnswer">
						{{btnString}}
<!-- 						<image src="../../static/img/test/yueliang.png" class="moon"></image>
						<image src="../../static/img/test/decorate.png" class="decorate"></image> -->
					</view>
				</view>
			</view>
		</view>
		<!-- <cover-view class="paragraphBox" :style="'top:' + customNavHeight + 'px;'" v-show="paragraphShow"> -->
		<cover-view class="paragraphBox" :style="'top:0;'" v-show="paragraphShow">
			<cover-image :src="'../../static/img/test/paragraphBG.jpg'|remoteImgSource" class="backImg"></cover-image>
			<cover-view class="pTitleWrap">
				<cover-view class="pTitle reflect1" v-show="info.bookname">
					<cover-image class="dec1" src="../../static/img/test/dec1.png"></cover-image>
					{{info.bookname}}
					<cover-image class="dec2" src="../../static/img/test/dec2.png"></cover-image>
				</cover-view>
			</cover-view>
			<cover-view class="pContent">
				{{paragraphContent}}
			</cover-view>
			<cover-view class="pClose reflect1" @click="closeParagraph">返回答题</cover-view>
		</cover-view>
		<get-coin @ensure="ensure" :show="getPointShow" :score="resultScore" :point="coin"></get-coin>
	</view>
</template>

<script>
	// import plugin from '../../common/js/playtts.js'
	import { mapMutations } from 'vuex'
	import {initialQue, initialTesting, earnCapacityPoint} from '../../common/api/book.js'
	import {queryTaskContent, querySA, addTaskResult,addTaskResultExt, beginAnswer, getPoint, queryTaskContentBK, beginAnswerBK, addTaskResultBK, queryTaskResultBK, getSimilarScoreV2} from '../../common/api/task.js'
	import getCoin from '../../components/get-point.vue'
	import cosBtn from '../../components/cos-btn.vue'
	import questionItem from '../../components/task2/question-item.vue'
	import {taskInfo, answerInfo} from './taskData.js'
	var imageData = ''
	export default {
		components:{
			cosBtn,
			questionItem,
			getCoin
		},
		provide() {
			return {
				questionPage: this
			}
		},
		data() {
			return {
				animationTimer: null,
				skipArr: [],
				customNavHeight: 100,
				isMakeUp: false,
				answerstatus: 0,
				point: 0,
				animationData: {},
				menuHeight: 60,
				menuPadding: 16,
				pageTitle: "评测",
				loaded: false,
				backOn: false,
				soundOn: false,
				//区分老师布置与自己评测
				isself: false,
				capacityscore: [],
				isevaluation: false,
				questionInfo: {},
				//评测信息
				info: {},
				infoShow: false,
				complete: false,
				//题目信息
				taskContent: {
					questions: []
				},
				//标准答案
				standardAnswer: {
					questions: []
				},
				//题目序号
				curIndex: 0,
				//连线题数据
				canvasWidth: 300,
				canvasHeight: 150,
				canvasRate: 1,
				ctx: null,
				ctxL: null,
				canvasRendered: false,
				leftList: [],
				rightList: [],
				moveFlag: false,
				lineStart: {},
				lineEnd: {},
				//用户连线答案
				curLineArr: [],
				curActive:{
					left: null,
					right: null
				},
				startItem: null,
				timer: null,
				time: 0,
				timeString: '',
				committing: false,
				innerAudioContext: null,
				rightSound: null,
				right3Sound: null,
				wrongSound: null,
				wrong3Sound: null,
				rightIterator: 0,
				wrongIterator: 0,
				correctCount: 0,
				wrongCount: 0,
				getPointShow: false,
				coin: 0,
				resultScore: 60,
				nextUrl: '',
				paragraphShow: false,
				exp: false //阅读力评测
			};
		},
		computed:{
			btnString(){
				let str = '确定'
				if(this.taskContent.questions && this.curIndex >= this.taskContent.questions.length - 1){
					str = '提交'
				}
				return str
			},
			curParagraph(){
				if(!this.currentQuestion || !this.currentQuestion.paragraphid || !this.taskContent.paragraphs){
					return ''
				}
				let idx = this.taskContent.paragraphs.findIndex(e=>e.paragraphid === this.currentQuestion.paragraphid)
				if(idx >= 0){
					return this.taskContent.paragraphs[idx].content
				}else{
					return ''
				}
			},
			isdisable(){
				let state =  (!this.complete) && (this.curIndex < (this.taskContent.questions.length - 1))
				return state
			},
			nextShow(){
				return this.curIndex < this.taskContent.questions.length - 1
			},
			taskType(){
				if(this.info.tasktype === 0){
					return '评测'
				}else if(this.info.tasktype === 1){
					return '写作'
				}else if(this.info.tasktype === 2){
					return '考试'
				}
				return '评测'
			},
			questionType(){
				if(!this.currentQuestion){
					return ''
				}
				switch(this.currentQuestion.questiontype){
					case 1:
						return '单选题'
					case 2:
						return '多选题'
					case 3:
						return '判断题'
					case 4: 
						return '连线题'
					case 5:
						return '排序题'
					case 6:
						return '填空题'
					case 7:
						return '判断题'
					case 8:
						return '填字题'
					case 9:
						return '问答题'
					default:
						return ''
				}
			},
			currentQuestion(){
				if(!this.taskContent){
					return {type: 1, title: ''}
				}
				if(this.taskContent.questions.length > 0){
					return this.taskContent.questions[this.curIndex]
				}
			},
			currentAnswer(){
				if(!(this.standardAnswer.questions instanceof Array) || !this.currentQuestion){
					return {type: 1}
				}
				let el = this.standardAnswer.questions.find((e, i)=>{
					return this.currentQuestion.questionid === e.questionid
				})
				return el || {type: 1}
			},
			paragraphContent(){
				if(this.currentQuestion && this.currentQuestion.paragraph){
					return this.currentQuestion.paragraph
				}else if(this.curParagraph){
					return this.curParagraph
				}
				return ''
			}
		},
		watch:{
			currentQuestion: {
				//initial question
				handler(val){
					if(!val){
						return {type: 1}
					}
					if(val.questiontype === 2){
						this.animationExe()
					}
				}
			}
		},
		async onLoad(option){
			
			//debug !!!!!
			// await this.init()
			// this.$store.state.user.token = uni.getStorageSync('token')
			this.animation = uni.createAnimation({
				duration: 600,
				timingFunction: 'ease',
			})
			uni.showLoading({
				title: '加载中'
			})
			this.isself = option.isself || false
			if(option.exp){
				this.exp = true
			}
			if(option.isMakeUp){
				this.isMakeUp = true
			}
			if(option.answerstatus){
				this.answerstatus = option.answerstatus * 1
			}
			if(option.fromIndex){
				this.isevaluation = true
				this.questionInfo = await initialQue({pageIndex: 1, pageSize: 200})
			}
			// 设置导航标题
			let title = '评测'
			if(option.isExam){
				title = '考试'
			}
			uni.setNavigationBarTitle({
				title
			})
			
			// this.loaded = true
			let screenWidth = 375, screenHeight = 667
			const sysInfo = uni.getSystemInfoSync()
			//#ifdef MP-WEIXIN
			screenWidth = sysInfo.windowWidth
			screenHeight = sysInfo.windowWidth
			//#endif
			//#ifdef H5
			if(sysInfo.screenWidth > sysInfo.screenHeight){
				screenHeight = 1080
				screenWidth = 607
				this.canvasRate = 607 / 375
			}else if(window.injectedObject){
				screenWidth = window.injectedObject.getW()
				screenHeight = window.injectedObject.getH()
			}else{
				screenWidth = window.innerWidth
				screenHeight = window.innerHeight
			}
			//#endif
			// this.canvasRate = screenWidth / 375
			// this.canvasWidth = screenWidth / 375 * 300
			// this.canvasHeight = this.canvasRate * 220
			// this.ctx = uni.createCanvasContext('myCanvas')
			// this.ctxL = uni.createCanvasContext('myCanvasL')
			// console.dir(option)
			
			this.info = uni.getStorageSync('excerciseInfo')
			// this.taskid = this.info.taskid
			if(option.taskid && option.taskid !== 'undefined'){
				this.taskid = option.taskid * 1
			}
			// console.dir(this.info)
			//检查是否有未答完的题目若有则获取缓存数据继续之前的答题
			const oldTask = uni.getStorageSync('taskContent')
			if(this.taskid && this.taskid === oldTask.taskid && !this.isevaluation){
				this.taskContent = oldTask
				if(oldTask.pointer >= oldTask.questions.length){
					oldTask.questions.length-1
				}
				this.curIndex = oldTask.pointer
				uni.hideLoading()
			}else{
				this.queryTaskContent()
			}
			
			this.querySA()
			// this.initTTSPlayer()
		},
		created(){
			this.innerAudioContext = uni.createInnerAudioContext()
			this.innerAudioContext.loop = true
			// this.innerAudioContext.src = '/static/music/back.mp3'
			// this.innerAudioContext.src = 'http://192.168.1.76:8090/just communication.mp3'
			// this.innerAudioContext.src = 'https://zhiyue.insyte.cn/media/music/last impression.mp3'
			this.innerAudioContext.src = 'https://zhiyue.insyte.cn/media/music/back.mp3'
			this.innerAudioContext.onPlay(()=>{
				console.log('开始播放了')
				this.backOn = true
			})
			this.innerAudioContext.onPause((res)=>{
				console.log('暂停播放')
				this.backOn = false
			})
			this.innerAudioContext.onError((res)=>{
				console.log('播放出错了')
				this.backOn = false
			})
			this.innerAudioContext.onCanplay(()=>{
				this.innerAudioContext.play()
			})
			this.soundLoading('rightSound')
			// this.backOn = true
		},
		mounted(){
		},
		onShow(){
			this.setTitle('阅读评测')
			this.animation  = uni.createAnimation({duration: 400, timingFunction: 'ease-in'})
		},
		
		beforeDestroy(){
			this.innerAudioContext.destroy()
			this.rightSound.destroy()
		},
		onHide(){
			if(this.innerAudioContext){
				this.innerAudioContext.stop()
			}
		},
		
		methods: {
			init(){
				let token = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IkY2QzIzQzVFRTc1M0ZGRjNFMjg4NTE4ODY4NzgwRDQwN0ZBNUIzQ0RSUzI1NiIsInR5cCI6ImF0K2p3dCIsIng1dCI6IjlzSThYdWRUX19QaWlGR0lhSGdOUUgtbHM4MCJ9.eyJuYmYiOjE2MzgzMjExMTksImV4cCI6MTYzODMyNDcxOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDIzIiwiY2xpZW50X2lkIjoiRGV2aWNlQ2xpZW50IiwianRpIjoiQUQ2Rjc4QzdDMEZFRjVFOUVBMEVDNzVEN0Y1Njc3QzMiLCJpYXQiOjE2MzgzMjExMTksInNjb3BlIjpbImRldmljZS5zY29wZSJdfQ.Noz5634jnwL8wal1XpI56L-wN5w25y577bTitp-kDmMrd61STK_-aUnnF-VbGol-hTUrtPa0ot5eUJFj2sXmhre78SCeNZLJEkVOnYiOzTHrzji1IyhitdZNUSXoQYM6EGfeM9vlna-DrTqp4qjHhSc_4r9Pxs1cJitRQy2Pd6YtDuQnep8ZM59j6GYrzmUnko3LlMRoKYba3MyrHJkyzsSWQsCqb7rJIC8P__I1LSooYw0xxJ86ZNYC8K7QQg47LnD40N7BGxnPMzD7-6rQ_fAAEJJY3N01hxRFGMs86I2CPbNsSmNWdsHycluJnEhkcL_v9pUMTozNRW2m0qUeHw'
				this.$store.commit('setToken', token)
				uni.setStorageSync('token', token)
			},
			// clearCanvas(){
			// 	this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
			// 	this.ctxL.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
			// },
			initTTSPlayer(){
				plugin.ttsPlayer.onEnded(()=>{
					this.soundOn = false
				})
				plugin.ttsPlayer.onError(()=>{
					this.soundOn = false
				})
				plugin.ttsPlayer.onStop(()=>{
					this.soundOn = false
				})
			},
			showcoin(){
				this.getPointShow = true
			},
			...mapMutations(['setInitialtesting']),
			animationExe(){
				if(this.questionType === '多选题'){
					this.animation.scale(1.4 + (Math.random() / 10), 1.4 + (Math.random() / 10)).step()
					this.animation.scale(1, 1).step({timingFunction: 'ease-out'})
					this.animationData = this.animation.export()
				}
			},
			updateAnswer(){
				let resItem = {}
				let right = false
				let AS
				try{
					let tempItem
					// AS = this.standardAnswer.questions[this.taskContent.pointer].standardanswers
					if(!this.currentQuestion){
						AS = ''
					}else{
						tempItem = this.standardAnswer.questions.find((e)=>{
							return e.questionid === this.currentQuestion.questionid
						})
						if(tempItem === undefined){
							this.$toast('标准答案丢失')
						}else{
							AS = tempItem.standardanswers
						}
					}
				}catch(err){
					console.log(err)
					this.$toast('标准答案解析错误')
					var logData = {
						msg: '标准答案解析错误',
						data: {
							taskid: this.taskContent.taskid,
							taskContent: this.taskContent.pointer,
							standardAnswer: this.standardAnswer
						},
						error: err.message,
						stack: err.stack
					}
					this.questionErrorLog(logData)
					this.skip()
				}
				//检测正误并整合答案
				if(this.currentQuestion.questiontype === 4){
					let qs = this.$refs['questionItem']
					if(this.scoreMark(JSON.stringify(qs.curLineArr), AS, qs.question.questiontype)){
						right = true
					}
					resItem = {
						questionid: qs.question.questionid,
						type: qs.question.questiontype,
						isanswer: qs.isanswer,
						answer: JSON.stringify(qs.curLineArr),
						right
					}
				}else{
					const child = this.$refs['questionItem']
					if(this.scoreMark(child.myanswer, AS, child.question.questiontype)){
						right = true
					}
					resItem = {
						questionid: child.question.questionid,
						type: child.question.questiontype,
						isanswer: child.isanswer,
						answer: child.myanswer,
						right
					}
					if(this.currentQuestion.questiontype !== 1 && this.currentQuestion.questiontype !== 3 && this.currentQuestion.questiontype !== 5 && this.currentQuestion.questiontype !== 7 && this.currentQuestion.questiontype !== 8 && this.currentQuestion.questiontype!== 9){
					// if(this.currentQuestion.questiontype !== 1  && this.currentQuestion.questiontype !== 5 && this.currentQuestion.questiontype !== 7 && this.currentQuestion.questiontype !== 8 && this.currentQuestion.questiontype!== 9){
						resItem.answer = JSON.stringify(resItem.answer)
					}
					if(this.currentQuestion.questiontype === 3 && resItem.answer !== ''){
						resItem.answer = JSON.stringify(resItem.answer)
					}
				}
				resItem = this.checkIsAnswer(resItem)
				this.taskContent.result[this.curIndex] = resItem
				
				uni.setStorageSync('taskContent', this.taskConten)
			},
			preProblem(){
				this.updateAnswer()
				this.taskContent.pointer--
				this.curIndex--
				// plugin.stopTTS()
			},
			nextProblem(){
				this.updateAnswer()
				this.taskContent.pointer++
				this.curIndex++
				try{
					var len = this.taskContent.questions.length - 1
					if(this.taskContent.pointer >= len){
						this.taskContent.pointer = len
						this.curIndex = len
					}
				}catch(err){
					console.log(err)
				}
				// plugin.stopTTS()
			},
			goBack(){
				uni.showModal({
					title: '警告',
					content: '您未提交回答，本次考试可能计分为0.',
					success(res){
						if(res.confirm){
							uni.navigateBack()
						}
					}
				})
			},
			setNavSize(){
				let sysinfo = uni.getSystemInfoSync()
				let statusHeight = sysinfo.statusBarHeight 
				let menuClient = uni.getMenuButtonBoundingClientRect()
				this.menuHeight = menuClient.height
				this.menuPadding = (menuClient.top - statusHeight) * 2
			},
			rotateToggle(){
				if(this.backOn){
					this.innerAudioContext.pause()
					this.backOn = false
				}else{
					this.innerAudioContext.play()
					this.backOn = true
				}
			},
			timeFormat(n){
				let h = Math.floor(n / 3600)
				if(h === 0){
					h = ''
				}else{
					h = h > 10 ? h : '0' + h
				}
				let m = Math.floor(n % 3600 / 60)
				m = m > 10 ? m : '0' + m
				let s = Math.floor(n % 3600 % 60)
				s = s > 10 ? s : '0' + s
				return h + ':' + m + ':' + s
			},
			async queryTaskContent(){
				if(this.isevaluation){
					//初次评测
					this.taskContent = {
						taskid: this.taskid,
						questions: this.questionInfo.questions
					}
				}else{
					//其他类型测试
					let res
					// if(this.isMakeUp){
					// 	if(this.answerstatus === 3){
					// 		res = await beginAnswerBK({taskid: this.taskid})
					// 	}
					// }else{
					// 	res = await beginAnswer({taskid: this.taskid})
					// }
					const params = {
						taskid: this.taskid,
						// studentid: this.$store.state.user.keyid
					}
					if(this.isMakeUp){
						this.taskContent = await queryTaskContentBK(params)
					}else{
						// this.taskContent = await queryTaskContent(params)
						this.taskContent = taskInfo
					}
				}
				this.taskContent = this.taskContent.data || {questions:[]}
				//题目类型排序
				this.taskContent.questions = this.sortQuestion(this.taskContent.questions)
				//添加要提交的数据进行本地缓存
				this.taskContent.taskid = this.taskid
				this.taskContent.pointer = 0
				this.curIndex = 0
				this.taskContent.result = new Array(this.taskContent.questions.length)
				this.taskContent.questions.forEach((e, i)=>{
					//初始化已填写答案
					let answer = e.useranswers
					if(e.questiontype === 2 && e.useranswers instanceof Array){
						answer = JSON.stringify(e.useranswers)
					}
					let resultItem = {
						questionid: e.questionid,
						type: e.questiontype,
						isanswer: e.isanswer,
						answer,
						right: e.right === null ? false : true
					}
					resultItem = this.checkIsAnswer(resultItem)
					this.taskContent.result[i] = resultItem
					e.idx = i
				})
				if(this.taskContent.remainingtime){
					this.taskContent.time = Math.floor(this.taskContent.remainingtime / 1e7)
					this.time = this.taskContent.time
					if(this.taskContent.remainingtime <= 0){
						this.time = 0
					}
				}
				// this.setTimer()
				uni.setStorageSync('taskContent', this.taskConten)
				uni.hideLoading()
			},
			async querySA(){
				if(this.isevaluation){
					this.standardAnswer = {
						taskid: this.taskid,
						questions: this.questionInfo.questions
					}
				}else{
					const params = {
						taskid: this.taskid,
						// studentid: this.$store.state.user.keyid
					}
					// this.standardAnswer = await querySA(params)
					this.standardAnswer = answerInfo
					this.standardAnswer = this.standardAnswer.data || {questions: []}
				}
				if(!this.standardAnswer.questions || this.standardAnswer.questions.length === 0){
					var logData = {
						msg: '标准答案丢失',
						data: {
							taskid: this.taskContent.taskid,
							standardAnswer: this.standardAnswer
						},
						error: ''
					}
					this.questionErrorLog(logData)
					this.skip()
				}else{
					this.loaded = true
				}
			},
			submitAnswer(){
				if(this.isdisable){
					return
				}
				let resItem = {}
				let right = false
				let AS
				try{
					let tempItem
					// AS = this.standardAnswer.questions[this.taskContent.pointer].standardanswers
					if(!this.currentQuestion){
						AS = ''
					}else{
						tempItem = this.standardAnswer.questions.find((e)=>{
							return e.questionid === this.currentQuestion.questionid
						})
						if(tempItem === undefined){
							this.$toast('标准答案丢失')
						}else{
							AS = tempItem.standardanswers
						}
					}
				}catch(err){
					console.log(err)
					this.$toast('标准答案解析错误')
					var logData = {
						msg: '标准答案解析错误',
						data: {
							taskid: this.taskContent.taskid,
							taskContent: this.taskContent.pointer,
							standardAnswer: this.standardAnswer
						},
						error: err.message,
						stack: err.stack
					}
					this.questionErrorLog(logData)
					this.skip()
				}
				//检测正误并整合答案
				if(this.currentQuestion.questiontype === 4){
					let qs = this.$refs['questionItem']
					if(this.scoreMark(JSON.stringify(qs.curLineArr), AS, qs.question.questiontype)){
						right = true
					}
					resItem = {
						questionid: qs.question.questionid,
						type: qs.question.questiontype,
						isanswer: qs.isanswer,
						answer: JSON.stringify(qs.curLineArr),
						right
					}
				}else{
					const child = this.$refs['questionItem']
					if(this.scoreMark(child.myanswer, AS, child.question.questiontype)){
						right = true
					}
					resItem = {
						questionid: child.question.questionid,
						type: child.question.questiontype,
						isanswer: child.isanswer,
						answer: child.myanswer,
						right
					}
					if(this.currentQuestion.questiontype !== 1 && this.currentQuestion.questiontype !== 3 && this.currentQuestion.questiontype !== 5 && this.currentQuestion.questiontype !== 7 && this.currentQuestion.questiontype !== 8 && this.currentQuestion.questiontype !== 9){
						resItem.answer = JSON.stringify(resItem.answer)
					}
					if(this.currentQuestion.questiontype === 3 && resItem.answer !== ''){
						resItem.answer = JSON.stringify(resItem.answer)
					}
				}
				resItem = this.checkIsAnswer(resItem)
				this.taskContent.result[this.curIndex] = resItem
				
				uni.setStorageSync('taskContent', this.taskConten)
				//点击提交按钮播放音效
				if(this.backOn){
					this.rightSound.stop()
					this.rightSound.seek(0)
					this.rightSound.play()
				}
				// window.injectedObject.stopMsg()
				this.soundOn = false
				if(this.taskContent.pointer < this.taskContent.questions.length - 1){
					//下一题
					this.curIndex++
					this.taskContent.pointer++
					try{
						var len = this.taskContent.questions.length - 1
						if(this.curIndex > len){
							this.curIndex = len
							this.taskContent.pointer = len
						}
					}catch(err){
						console.log(err)
					}
					this.complete = false
					// child.initData()
				}else{
					//提交试卷
					// var unCompleteIdx = this.taskContent.result.findIndex(e=>!e.isanswer)
					var unCrossArr = this.taskContent.result.filter((e, i)=>{
						return this.skipArr.indexOf(i) < 0
					})
					var unCompleteIdx = unCrossArr.findIndex(e=>!e.isanswer)
					if(unCompleteIdx > -1 && unCompleteIdx !== (this.taskContent.questions.length - 1)){
						uni.showModal({
							title: '警告',
							content: `第${unCompleteIdx + 1}题未作答，仍然确定要提交吗？`,
							cancelText: '确定提交',
							confirmText: '返回作答',
							success: (res)=>{
								if(res.confirm){
									this.curIndex  = unCompleteIdx
									this.taskContent.pointer = unCompleteIdx
									// plugin.stopTTS()
									this.complete = false
								}
								if(res.cancel){
									this.addTaskResult()
								}
							}
						})
					}else{
						this.addTaskResult()
					}
				}
			},
			skip(){
				let num = this.curIndex
				if(this.skipArr.indexOf(num) < 0){
					this.skipArr.push(num)
				}
				if(this.taskContent.curIndex < this.taskContent.questions.length - 1){
					this.curIndex++
					this.taskContent.pointer++
					try{
						var len = this.taskContent.questions.length - 1
						if(this.taskContent.pointer >= len){
							this.taskContent.pointer = len
							this.curIndex = len
						}
					}catch(err){
						console.log(err)
					}
					this.complete = false
				}else{
					this.addTaskResult()
				}
			},
			async addTaskResult(){
				if(this.committing){
					return
				}
				
				this.committing = true
				this.taskContent.rightcount = 0
				this.taskContent.wrongcount = 0
				if(!this.taskContent.misscount){
					this.taskContent.misscount = 0
				}
				this.taskContent.result.forEach((e, i)=>{
					const myanswer = e.answer
					let tempItem = this.standardAnswer.questions.find((a,ai)=>{
						// return a.questionid === this.taskContent.questions[i].questionid
						return a.questionid === e.questionid
					})
					const AS = tempItem === undefined ? '' : tempItem.standardanswers
					// const AS = this.standardAnswer.questions[i].standardanswers
					if(this.scoreMark(myanswer, AS, e.type)){
						if(e.questiontype !== 9){
							this.taskContent.rightcount++
							if(this.taskContent.questions[i].capacityscore){
								this.capacityscore = this.capacityscore.concat(this.taskContent.questions[i].capacityscore)
							}
						}
					}else{
						if(e.questiontype !== 9){
							this.taskContent.wrongcount++
						}
					}
				})
				try {
					const essays = []					
					this.taskContent.result.forEach(e => {
					  if (e.questiontype === 9) {
						essays.push({
						  questionId: e.questionid,
						  text: e.answer
						})
					  }
					})
					if(essays.length > 0){
						const simRes = await getSimilarScoreV2({ info: essays })
						const simScore = simRes.data
						this.taskContent.result.forEach((e, i) => {
							const simIndex = simScore.findIndex(scoreItem => scoreItem.questionid === e.questionid)
							if (simIndex >= 0) {
								this.taskContent.result[i].similarityScore = simScore[simIndex].score
								this.taskContent.result[i].right = false
								if (simScore[simIndex].score === 1) {
									this.taskContent.result[i].right = true
									this.taskContent.rightcount++
								} else {
									this.taskContent.wrongcount++
								}
							}
						})
					}
				} catch (err) {
				    console.log(err)
				}
				this.taskContent.status = 2
				let params = {
					 rightcount: this.taskContent.rightcount,
					 wrongcount: this.taskContent.wrongcount,
					 misscount: this.taskContent.misscount,
					 result: this.taskContent.result,
					 status: 2
				}
				let nextPage = ''
				if(this.isevaluation){
					
					params.testingid = this.taskid
					let gradeInfo = {}
					try{
						gradeInfo = await initialTesting(params)
					}catch(err){
						this.committing = false
						console.log(err)
					}
					this.coin = gradeInfo.point
					this.resultScore = gradeInfo.accuracy
					if(gradeInfo.info){
						this.resultScore = gradeInfo.info.score
					}
					
					// this.showcoin()
					// if(this.coin && this.coin > 0){
					// 	this.showcoin()
					// }
					this.setInitialtesting(true)
					await earnCapacityPoint({
						testingrecordid:  gradeInfo.info.testingrecordid,
						capacityscore: this.capacityscore
					})
					this.committing = false
					nextPage = `/pages/test/evaluation?taskid=${gradeInfo.info.testingrecordid}`
				}else{
					params.taskid = this.taskContent.taskid
					let gradeInfo = {}
					try{
						if(this.isMakeUp){
							gradeInfo = await addTaskResultBK(params)
						}else{
							// gradeInfo = await addTaskResult(params)
							// if(this.exp){
							// 	gradeInfo = this.sattleResultExt(params)
							// }else{
								gradeInfo = this.sattleResult(params)
							// }
						}
						gradeInfo = gradeInfo.data||{}
					}catch(err){
						this.committing = false
						console.log(err)
					}
					this.resultScore = gradeInfo.score
					this.coin = gradeInfo.point
					// this.showcoin()
					// if(this.coin && this.coin > 0){
					// 	this.showcoin()
					// }
					//扣除任务数目
					// if(!this.isMakeUp){
					// 	await getPoint({
					// 		taskresultid: gradeInfo.taskresultid,
					// 		capacityscore: this.capacityscore
					// 	})
					// }
					uni.setStorageSync('capacityscore', this.capacityscore)
					this.committing = false					
					nextPage = `/pages/test2/testResult?taskid=${this.taskContent.taskid}`
					if(this.isself){
						nextPage += `&isself=true`
					}
					if(this.isMakeUp){
						nextPage += '&isMakeUp=true'
					}
					if(this.exp){
						nextPage += '&exp=true'
					}
					
				}
				
				clearInterval(this.timer)
				this.nextUrl = nextPage
				uni.redirectTo({
					url: this.nextUrl
				})
				// setTimeout(function(){
				// 	uni.redirectTo({
				// 		url: nextPage
				// 	})
				// }, 1000)
			},
			ensure(){
				console.log('ensure')
				console.log(this.nextUrl)
				if(this.nextUrl){
					uni.redirectTo({
						url: this.nextUrl
					})
				}
			},
			//比对标准答案评判正误
			scoreMark(ma, as, type){
				try{
					if(type === 1 ||  type === 7 || type === 9){
						if(typeof as === 'string'){
							as = as.trim()
						}
						return ma === as
					}
					if(type === 8){
						if(typeof ma === 'string'){
							return JSON.parse(ma).join('|') === as.join('|')
						}else{
							return false
						}
					}
					if(type === 5){
						if(/，/.test(as)){
							//手动录入的排序题
							return ma === as
						}else{
							//表格导入的
							return ma.replace(/，/g,'') === as
						}
					}
					let arr = ma
					if(typeof ma === 'string'){
						arr = JSON.parse(ma)
					}
					let res = true	
					if(type === 2){
						if(arr.length !== as.length){
							res = false
							return res
						}
						const arr1 = arr.sort()
						const arr2 = as.sort()
						for(let k=0;k<arr1.length;k++){
							if(arr1[k] !== arr2[k]){
								res = false
								break
							}
						}
						return res
					}
					if(arr === ''){
						arr = []
					}
					for(let i=0;i<as.length;i++){
						let answerIndex = arr.findIndex((e)=>{
							if(type === 3 || type === 6){
								return e.index === as[i].index && e.result === as[i].result
							}else if(type === 4){
								return e.indexleft === as[i].indexleft && e.indexright === as[i].indexright
							}
						})
						if(answerIndex < 0){
							res = false
							break
						}
					}
					return res
				}catch(err){
					console.log(type)
					console.log(ma)
					console.log(as)
					console.log('err')
					console.log(err)
				}
			},
			//检查是否作答
			checkIsAnswer(item){
				try{
					let {type, answer} = item
					item.isanswer = true
					if((type === 2 || type === 4) && answer && (typeof answer === 'string')){
						answer = JSON.parse(answer)
					}
					if(answer === undefined || answer === null || answer === '' || (answer instanceof Array && answer.length === 0)){
						item.isanswer = false
						return item
					}
					if(type === 3 && answer[0].result === ''){
						item.isanswer = false
						return item
					}
					if(type === 8 && answer){
						var arr = JSON.parse(answer)
						item.isanswer = (arr.length > 0)
						return item
					}
					if(type === 6){
						if(typeof answer === 'string'){
							answer = JSON.parse(answer)
						}
						let miss = answer.every(e=>e.result === '')
						if(miss){
							item.isanswer = false
						}
					}
					return item
				}catch(err){
					console.log(err)
					this.$toast('题目无法正确解析')
					var logData = {
						msg: '检验是否作答出错',
						data: {
							taskid: this.taskContent.taskid,
							item
						},
						error: err.message,
						stack: err.stack
					}
					this.questionErrorLog(logData)
					this.skip()
				}finally{
					return item
				}
			},
			
			sattleResult(params){
				const result = {
					accuracy: 0,
					misscount: params.misscount,
					paragraphs: null,
					questions: [{
						standardanswers: "C",
						stems: [{index: "A", content: "直线"},{index: "B", content: "线段"},{index: "C", content: "垂直线"},{index: "D", content: "曲线"}],
						title: '测量纬度的方法，都是以（）为标准的。',
						type: 1,
						useranswers: "A"
					}],
					rightcount: params.rightcount,
					tasktitle: this.taskContent.tasktitle,
					wrongcount: params.wrongcount
				}
				result.accuracy = Math.floor(params.rightcount / (params.rightcount + params.wrongcount + params.misscount) * 100) 
				result.questions = this.taskContent.questions.map(e=>{
					let resultItem = params.result.find(el=>el.questionid === e.questionid)
					if(resultItem){
						e.useranswers = resultItem.answer
						e.right = resultItem.right
					}
					let answer = this.standardAnswer.questions.find(item=>item.questionid === e.questionid)
					if(answer){
						e.standardanswers =  answer.standardanswers
					}
					return e
				})
				uni.setStorageSync('testResult', result)
				return {
					score: result.accuracy,
					point: 0,
					taskresultid: ''
				}
			},
			/***********/
			soundLoading(type){
				this[type] = uni.createInnerAudioContext()
				this[type].src = `https://zhiyue.insyte.cn/media/music/${type}.mp3`
				this[type].onError((res)=>{
					console.log('音效播放出错了')
				})
				console.log('可以播放音效了')
			},
			playSound(ma, AS, type){
				const goal = this.scoreMark(ma, AS, type)
				if(goal){
					this.wrongIterator = 0
					this.rightIterator++
					if(this.rightIterator >= 3){
						this.right3Sound.play()
					}else{
						this.rightSound.play()
					}
				}else{
					this.rightIterator = 0
					this.wrongIterator++
					if(this.wrongIterator>=3){
						this.wrong3Sound.play()
					}else{
						this.wrongSound.play()
					}
				}
			},
			//刷新任务列表
			updateTaskList(){
				const pages = getCurrentPages()
				pages.forEach(e=>{
					if(/pages\/test\/index/.test(e.route)){
						const idx = e.$vm.taskList.findIndex(el=>el.taskid === this.taskid)
						if(idx >= 0){
							// e.$vm.$set(e.$vm.taskList[idx].studenttest, 'answerstatus', 2)
							e.$vm.initList()
						}
					}
				})
			},
			speekTitle(){
				// plugin.stop()
				if(!this.soundOn){
					let content = ''
					if(this.currentQuestion.questiontype === 3){
						content = this.currentQuestion.stems[0].content
					}else{
						content = this.currentQuestion.title
					}
					content = this.concatAnswerString(content)
					this.soundOn = true
					// plugin.playTTS(content)
					if(window.injectedObject){
						window.injectedObject.speckMsg(content)
					}
				}else{
					// this.stopSpeek()
					if(window.injectedObject){
						window.injectedObject.stopMsg()
						this.soundOn = false
						this.$log('已经点击暂停读题了')
					}
				}
			},
			concatAnswerString(str){
				const type = this.currentQuestion.questiontype
				if(type === 1 || type === 2 || type === 5){
					this.currentQuestion.stems.forEach(e=>{
						str += ' '
						if(e.index === '2' || e.index === 2){
							str += '二'
						}else if(e.index === 'A'){
							str += '欸'
						}else{
							str += e.index
						}
						str += e.content
					})
				}
				if(type === 4){
					this.currentQuestion.stems.forEach(e=>{
						str += ' '
						str += e.stemleft.content
						str += ' '
						str += e.stemright.content
					})
				}
				return str
			},
			sortQuestion(arr){
				arr = arr.map(e => {
					e.sortStamp = e.questiontype === 7 ? 3 : e.questiontype
					return e
				})
				return arr.sort((a, b)=> {
					return a.sortStamp - b.sortStamp
				})
			},
			questionSortHandler(pre, nex){
				const power1 = pre.paragraphid ? pre.paragraphid.charCodeAt() : -1
				const power2 = nex.paragraphid ? nex.paragraphid.charCodeAt() : -1
				if (power1 === power2) {
					return pre.questiontype - nex.questiontype

				} else {
					return power1 - power2
				}
			},
			stopSpeek(){
				this.soundOn = false
				// plugin.stopTTS()
				// plugin.stop()
				if(window.injectedObject){
					window.injectedObject.stopMsg()
				}
			},
			openParagraph(){
				this.paragraphShow = true
			},
			closeParagraph(){
				this.paragraphShow = false
			}
		}
	}
</script>

<style lang="scss" scoped>
@import '../../common/style/public.css';
$color: #13227a;
.subject{
	position: relative;
	margin-right: 74rpx;
	margin-bottom: 10px;
	margin-left: 76rpx;
	// margin-right: 74rpx;
	&:before{
		content: '';
		position: absolute;
		width: 16rpx;
		top: 0;
		bottom: 0;
		left: -36rpx;
		border-radius: 8rpx;
		background: #2C95F8;
	}
}
.backgroundImage{
	position: fixed;
	width: 100%;
	height: 100%;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 0;
}
.exerciseHeader{
	position: relative;
	z-index: 1;
	padding: 30rpx;
	background: #F6F8FA;
	.infoToggle{
		margin-left: 306rpx;
		width: 140rpx;
		heigth: 50rpx;
		border-radius: 25rpx;
		background: #2C95F8;
		color: #ffffff;
		font-size: 0;
		line-height: 50rpx;
		text-align: center;
		text{
			font-size: 24rpx;
		}
		image{
			width: 16rpx;
			height: 14rpx;
			margin-right: 6rpx;
			border-radius: 16rpx;
			overflow: hidden;
		}
	}
	.toggleBox.undercover{
		height: 0;
		margin-bottom: 0;
	}
	.toggleBox{
		position: relative;
		margin-bottom: 30rpx;
		overflow: hidden;
		.dt{
			width: 180rpx;
			margin-bottom: 10rpx;
		}
		.dl{
			width: 360rpx;
		}
		.exerciseSurface{
			position: absolute;
			top: 0;
			right: 0;
			width: 140rpx;
			height: 180rpx;
		}
	}
}
.testPager{
	position: relative;
	padding-top: 30rpx;
	.questionChange{
		padding: 15px 60rpx;
		position: relative;
		.changeBtn{
			position: relative;
			display: inline-block;
			// width: 136rpx;
			width: 50rpx;
			height: 50rpx;
			font-size: 31rpx;
			text-align: center;
			line-height: 50rpx;
			// padding: 3px 8px;
			color: #ffffff;
			background-color: #2C95F8;
			background: url('../../static/img/test/next2.png');
			background-size: 100% 100%;
			// border-radius: 8px;
			// box-shadow: 7rpx 7rpx 5rpx rgba(0,102,255,.15);
		}
		.changeBtn.left{
			transform-origin: 50% 50%;
			transform: rotate(180deg);
		}
		// .btnHover{
		// 	color: white;
		// 	background-color: #82c6f4;
		// }
		text{
			color:#171cbb;
			font-size: 36rpx;
			position: absolute;
			top: 15px;
			left: 50%;
			transform: translateX(-50%);
		}
	}
	.stateBar{
		padding-left: 40rpx;
		font-size: 28rpx;
		color: #2c95f8;
		line-height: 60rpx;
		.restTime{
			padding: 10rpx 20rpx;
			margin-right: 32rpx;
			background: #EBF6FF;
			border-radius: 8rpx;
			overflow: hidden;		
			.clock{
				width: 32rpx;
				height: 32rpx;
				vertical-align: -10%;
				margin-right: 20rpx;
			}
		}
		.progress{
			padding: 10rpx 0;
			.groove{
				display: inline-block;
				width: 250rpx;
				heigth: 16rpx;
				margin-left: 18rpx;
				vertical-align: 5%;
				border-radius: 8rpx;
				overflow: hidden;
				background: #EBF6FF;
				.stuffing{
					height: 16rpx;
					border-radius: 8rpx;
					overflow: hidden;
					width: 0%;
					transition: width 0.3s;
					background: #2C95F8;
				}
			}
			.grooveAllScreen{
				width: 560rpx;
			}
		}
	}
	.questionArea{
		padding-top: 30rpx;
		padding-bottom: 50rpx;
		position: relative;
		z-index: 1;
		.toolbar{
			position: relative;
			margin-bottom: 30px;
			text-align: right;
			.backMusic{
				animation: rotate 2s linear infinite;
			}
			image{
				width: 40rpx;
				height: 40rpx;
				margin-right: 30px;
			}
			.questionType{
				position: absolute;
				left: 50%;
				top: 0;
				transform: translateX(-50%);
				width: 180rpx;
				height: 56rpx;
				line-height: 56rpx;
				color: #ffffff;
				background-color: #af4d4d;
				border-radius: 28rpx;
				display:none;
				// box-shadow: 7rpx 7rpx 5rpx rgba(232,142,12,.2);
				// .dec1{
				// 	position: absolute;
				// 	width: 33rpx;
				// 	height: 60rpx;
				// 	left: -25rpx;
				// 	top: -9rpx;
				// }
				// .dec2{
				// 	position: absolute;
				// 	width: 53rpx;
				// 	height: 50rpx;
				// 	right: -32rpx;
				// 	top: -7rpx;
				// 	margin-right: 0;
				// }
			}
			.reader{
				position: absolute;
				left: 52rpx;
				top: 3rpx;
				width: 136rpx;
				height: 52rpx;
				line-height: 52rpx;
				color: #ffffff;
				background-color: #eb7178;
				border-radius: 16rpx;
				box-shadow: 7rpx 7rpx 5rpx rgba(255,51,0,.2);
			}
		}
		.tip{
			font-size: 30rpx;
			color: #2CA1FF;
			image{
				vertical-align: middle;
				width: 32rpx;
				height: 32rpx;
			}
		}
	}
	.nextOne{
		margin-top: 100rpx;
		.submit{
			position: relative;
			color: white;
			width: 406rpx;
			height: 100rpx;
			font-size: 46rpx;
			text-align: center;
			line-height: 100rpx;
			margin: 0 auto;
			border-radius: 50rpx;
			background-color: #2a3dc5;
			// background-image: url('../../static/img/test/reflectLight.png');
			// background-repeat: no-repeat;
			// background-position: 8rpx 8rpx;
			// background-size: 42rpx 48rpx;
			.moon{
				position: absolute;
				z-index: -1;
				right: -30rpx;
				top: -25rpx;
				width: 95rpx;
				height: 95rpx;
			}
			.decorate{
				position: absolute;
				width: 105rpx;
				height: 120rpx;
				top: -18rpx;
				right: -20rpx;
			}
		}
		.disSubmit{
			background-color: #7174d1;
		}
	}
}
//自定义导航条
.custom-navbar{
	background: #ffffff;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	border-bottom: 1px solid rgba(0,0,0,0.1);
}
.statusBar{
	width: 100%;
	// height: var(--status-bar-height);
	height: 16px;
}
.navBar{
	box-sizing: border-box;
	height: 88px;
	box-sizing: border-box;
	padding-top: 12px;
}
@keyframes rotate{
	from{transform: rotate(0)}
	to{transform: rotate(360deg)}
}
//段落弹窗
.paragraphBox{
	position: fixed;
	z-index: 20;
	padding-top: 10rpx;
	top: 64px;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: transparent;
	// background-image: url('../../static/img/test/paragraphBG.jpg');
	// background-size: 100% 100%;
	color: #323388;
	.backImg{
		position: absolute;
		z-index: -1;
		top:0;
		left:0;
		right: 0;
		bottom: 0;
	}
	.pTitleWrap{
		position: relative;
		text-align: center;
		height: 120rpx;
		.pTitle{
			font-size: 35rpx;
			overflow: visible;
			display: inline-block;
			position: relative;
			top: 20px;
			// width: 184rpx;
			padding: 0 30rpx;
			height: 53rpx;
			margin: 0 auto;
			line-height: 53rpx;
			text-align: center;
			border-radius: 18rpx;
			background-color: #ffcc33;
			color: #ffffff;
			.dec1{
				position: absolute;
				width: 33rpx;
				height: 60rpx;
				left: -25rpx;
				top: -9rpx;
			}
			.dec2{
				position: absolute;
				width: 53rpx;
				height: 50rpx;
				right: -32rpx;
				top: -7rpx;
				margin-right: 0;
			}
		}
	}
	.pContent{
		padding: 40rpx 50rpx;
		margin: 24rpx 60rpx 0;
		border-radius: 25rpx;
		background-color: #eff6e6; 
		font-size: 40rpx;
		color: #339999;
		height: 55%;
		overflow: scroll;
		word-break: break-all;
		white-space: pre-wrap;
	}
	.pClose{
		width: 234rpx;
		height: 70rpx;
		font-size: 40rpx;
		line-height: 70rpx;
		text-align: center;
		color: #ffffff;
		margin: 34rpx auto;
		background-color: #2ca1ff;
		border-radius: 28rpx;
	}
}
</style>
